package sample.note;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import lombok.SneakyThrows;
import sample.note.storage.Repository;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Map;

import static sample.note.storage.Repository.COLUMN_TXT;

public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    EditText keyword;
    ListView lv;
    NotesAdapter adapter;
    SearchHandler searchHandler;
    int DELAY = 1024;
    private Repository repo;
    private ClipboardManager clipboard;

    @SneakyThrows
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        repo = new Repository(this);

        keyword = findViewById(R.id.keyword);
        SearchWatcher watcher = new SearchWatcher();
        keyword.addTextChangedListener(watcher);

        lv= findViewById(R.id.search_list);
        ArrayList<Map<String, String>> data= new ArrayList<>();
        adapter = new NotesAdapter(data, this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);

        searchHandler = new SearchHandler();
        clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map<String, String> data = adapter.getItem(position);
        assert data != null;
        String txt = data.get(COLUMN_TXT);
        ClipData clip = ClipData.newPlainText(txt.substring(0, 8), txt);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(getApplicationContext(), "Copied", Toast.LENGTH_SHORT).show();
    }

    class SearchHandler extends Handler{
        @SneakyThrows
        @Override
        public void handleMessage(Message msg) {

            String str = keyword.getText().toString();
            // lower pressure for database
            if (!msg.obj.toString().equals(str))
                return;

            ArrayList<Map<String, String>> list = repo.search(str);
            adapter.notifyChanged(list);

        }
    }
    class SearchWatcher extends TextWatcherWrapper{
        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() > 0 && s.toString().trim().length() > 0) {
                Message msg = Message.obtain();
                msg.obj = s.toString();
                searchHandler.sendMessageDelayed(msg, DELAY);
            }
        }
    }
}
